package com.bdc.whatwhat.authentification;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;

/**
 * Created by dev-w8-gfi on 28/05/2014.
 */
public class GPlus implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {

    private static final String TAG = "GOOGLE PLUS";
    private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

    private ProgressDialog mConnectionProgressDialog;
    private PlusClient mPlusClient;
    private ConnectionResult mConnectionResult;

    Activity activity;



    public interface GPlusDelegate{
        public void onGPlusConnected(PlusClient client,String token);
    }

    GPlusDelegate delegate;

    public GPlus(Activity activity, GPlusDelegate delegate) {
        this.activity = activity;
        this.delegate = delegate;

        mPlusClient = new PlusClient.Builder(activity, this, this)
                .setVisibleActivities("http://schemas.google.com/AddActivity",
                        "http://schemas.google.com/BuyActivity")
                .build();
        // Barre de progression à afficher si l'échec de connexion n'est pas résolu.
        mConnectionProgressDialog = new ProgressDialog(activity);
        mConnectionProgressDialog.setMessage("Signing in...");
    }

    public void connect() {
        if (mConnectionResult == null) {
            mConnectionProgressDialog.show();
            mPlusClient.connect();
        } else {
            try {
                mConnectionResult.startResolutionForResult(activity, REQUEST_CODE_RESOLVE_ERR);
            } catch (IntentSender.SendIntentException e) {
                // Nouvelle tentative de connexion
                mConnectionResult = null;
                mPlusClient.connect();
            }
        }
    }

    public void onStart() {
        mPlusClient.connect();
    }

    public void onStop() {
        mPlusClient.disconnect();
    }

    public void disconnect() {
        mPlusClient.clearDefaultAccount();
        mPlusClient.disconnect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (mConnectionProgressDialog.isShowing()) {
            // L'utilisateur a déjà appuyé sur le bouton de connexion. Commencer à résoudre
            // les erreurs de connexion. Attendre jusqu'à onConnected() pour masquer la
            // boîte de dialogue de connexion.
            if (result.hasResolution()) {
                try {
                    result.startResolutionForResult(activity, REQUEST_CODE_RESOLVE_ERR);
                } catch (IntentSender.SendIntentException e) {
                    mPlusClient.connect();
                }
            }
        }

        // Enregistrer l'intention afin que nous puissions lancer une activité lorsque
        // l'utilisateur clique sur le bouton de connexion.
        mConnectionResult = result;
    }

    public void onActivityResult(int requestCode, int responseCode, Intent intent) {
        if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == activity.RESULT_OK) {
            mConnectionResult = null;
            mPlusClient.connect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        String accountName = mPlusClient.getAccountName();
        //  Toast.makeText(activity, accountName + " is connected.", Toast.LENGTH_LONG).show();
        mConnectionProgressDialog.dismiss();

        if(delegate != null && mPlusClient != null) {
            AsyncTask task = new AsyncTask() {
                @Override
                protected Object doInBackground(Object... params) {
                    return getToken();
                }

                @Override
                protected void onPostExecute(Object token) {
                    super.onPostExecute(token);
                    delegate.onGPlusConnected(mPlusClient, (String)token);
                }
            };
            task.execute((Void)null);
        }
    }

    @Override
    public void onDisconnected() {
        Log.d(TAG, "disconnected");
    }

    private Person getProfile() {
        return mPlusClient.getCurrentPerson();
    }

    private String getToken(){
        String token = null;

        try {
            String scope = "oauth2:" + Scopes.PLUS_LOGIN;

            token = GoogleAuthUtil.getToken(activity,
                    mPlusClient.getAccountName(), scope);
        }catch (Exception e){
            e.printStackTrace();
        }

        return token;
    }

}
